package org.example.listener;

import cn.hutool.core.util.StrUtil;
import org.example.component.LoginInfo;
import org.example.component.UserInfo;
import org.example.packets.bean.Group;
import org.example.service.GroupService;
import org.example.util.ChannelContextUtil;
import org.tio.core.ChannelContext;

import java.util.List;

public class ImServerGroupPropListener implements ImGroupPropListener {

    private final GroupService groupService;

    public ImServerGroupPropListener() {
        this.groupService = new GroupService();
    }


    @Override
    public void onPropChange(Group group) {
        Group groupData = groupService.getGroupInfo(group.getRoomId());

        groupData.setRoomName(StrUtil.isNotBlank(group.getRoomName()) ? group.getRoomName() : groupData.getRoomName());
        groupData.setAvatar(StrUtil.isNotBlank(group.getAvatar()) ? group.getAvatar() : groupData.getAvatar());


        List<ChannelContext> channelContexts = ChannelContextUtil.groupUsers(group.getRoomId());
        for (ChannelContext channelContext : channelContexts) {
            LoginInfo loginInfo = new LoginInfo().setChannelContext(channelContext);
            Group cacheGroup = loginInfo.getGroupsMap().get(group.getRoomId());
            cacheGroup.setAvatar(groupData.getAvatar());
            cacheGroup.setRoomName(groupData.getRoomName());
            loginInfo.putGroup(cacheGroup);
        }

        groupService.updateById(groupData);

    }

    @Override
    public void onReadMessage(String roomId) {
        List<ChannelContext> channelContexts = ChannelContextUtil.contextList(UserInfo.id());
        for (ChannelContext channelContext : channelContexts) {
            LoginInfo loginInfo = new LoginInfo().setChannelContext(channelContext);

            Group cacheGroup = loginInfo.getGroupsMap().get(roomId);
            cacheGroup.setUnreadCount(0);

            loginInfo.putGroup(cacheGroup);
        }
    }

}
